<?php

namespace Profile;

use C\L\WebUserController;
use C\M\GroupBuyingOrder;

class GroupBuyingOrderController extends WebUserController
{
  /**
   * 列表接口
   **/
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);
        $builder = $this
            ->modelsManager
            ->createBuilder()
            ->columns(['id', 'sn', 'amount', 'payment_amount', 'state'])
            ->from('C\M\GroupBuyingOrder')
            ->andWhere('user_id = :user_id:', ['user_id' => $this->uid])
            ->orderBy('id DESC');

        $result = $this->paginationByBuilder($builder, $currentPage, $perPage);

        return $this->success($result);
    }

  /**
   * 详情接口
   **/
    public function showAction()
    {
        $id = $this->request->getQuery('id', 'int', 0);

        $order = GroupBuyingOrder::findFirst([
            'conditions' => 'id = :id: AND user_id = :user_id:',
            'bind' => [
                'id'      => $id,
                'user_id' => $this->uid,
            ],
        ]);

        if (!$order) {
            return $this->error('未查询到该团购信息');
        }

        [
            'goods'        => $goods,
            'group_buying' => $groupBuying,
            'commission'   => $commission,
        ] = json_decode($order->other_info, true);

        $orderData = [
            'sn'             => $order->sn,
            'quantity'       => $order->quantity,
            'amount'         => $order->amount,
            'payment_amount' => $order->payment_amount,
            'state'          => $order->state,
            'addtime'        => date('Y-m-d H:i:s', $order->addtime),
        ];

        $goods['thumbnail'] = $goods['thumbnail'] ?? null;

        $commission['profit'] = $this->s_itemaprlist->getProfitFromOrder($order);

        $result = [
            'order'        => $orderData,
            'goods'        => $goods,
            'group_buying' => $groupBuying,
            'commission'   => $commission,
        ];

        return $this->success($result);
    }
}
